﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using KorleBu.Application_Classes;

namespace KorleBu
{
    public partial class Items : System.Web.UI.Page
    {
        #region Class State Variables

        public Application_Classes.ItemSearch itemSearch = new Application_Classes.ItemSearch();
        public DataSet items = new DataSet();
        string cost;

        /// <summary>
        /// Dataset object, used for housing user method calls results.
        /// </summary>
        DataSet ds = new DataSet();
        /// <summary>
        /// Presentation object that accesses the presentation object classes methods.
        /// Used for accessing business methods for the user page.
        /// </summary>
        Presentation presentation = new Presentation();

        #endregion

        ////Jason Vance 10-31-12; Lazy initialize the label found on MasterPage.Master
        //private Label _lblMasterError = null;
        //private Label lblMasterError
        //{
        //    get
        //    {
        //        if (_lblMasterError == null)
        //            _lblMasterError = (Label)Master.FindControl("lblMasterError");
        //        return _lblMasterError;
        //    }
        //}

        #region Page Load
        protected void Page_Load(object sender, EventArgs e)
        {
            lblLoggedInUser.Text = "You are logged in as " + GetFirstName() + " " + GetLastName();

            if (!IsPostBack)
            {
                populateDropDownLists();
                TabContainer_ActiveTabChanged(TabContainer1, null);  //initializes the tab index to the starting index

                //show a message for pending tasks if the given user has tasks to do.  
                //This should only apply to store managers, general managers, CEOs, and Procurement
                if (GetIsStoreManager())
                {
                    ds = presentation.GetPendingRequests(GetStoreID());
                    if (ds.Tables.Count > 0) // If the method returned successfully
                    {
                        if (ds.Tables[0].Rows[0][0].ToString() != "") // if errors have occurred
                        {
                            //lblMasterError.Text = ds.Tables[0].Rows[0][0].ToString(); // Error message
                        }
                        else
                        {
                            //lblSideBarContent.Text = "**You have pending satellite store requests to handle.**";
                        }
                    }
                }
                else if (GetIsGeneralManager())
                {
                    ds = presentation.GetRequisitionsByPendingStatus();
                    if (ds.Tables.Count > 0) // If the method returned successfully
                    {
                        if (ds.Tables[0].Rows[0][0].ToString() != "") // if errors have occurred
                        {
                            //lblMasterError.Text = ds.Tables[0].Rows[0][0].ToString(); // Error message
                        }
                        else
                        {
                            //lblSideBarContent.Text = "**You have pending requisitions to handle.**";
                        }
                    }
                }
                else if (GetIsCEO())
                {
                    ds = presentation.GetRequisitionsByGMStatus();
                    if (ds.Tables.Count > 0) // If the method returned successfully
                    {
                        if (ds.Tables[0].Rows[0][0].ToString() != "") // if errors have occurred
                        {
                            //lblMasterError.Text = ds.Tables[0].Rows[0][0].ToString(); // Error message
                        }
                        else
                        {
                            //lblSideBarContent.Text = "**You have pending requisitions to handle.**";
                        }
                    }
                }
                else if (GetIsProcurement())
                {
                    ds = presentation.GetRequisitionsByCEOStatus();
                    if (ds.Tables.Count > 0) // If the method returned successfully
                    {
                        if (ds.Tables[0].Rows[0][0].ToString() != "") // if errors have occurred
                        {
                            //lblMasterError.Text = ds.Tables[0].Rows[0][0].ToString(); // Error message
                        }
                        else
                        {
                            //.Text = "**You have pending requisition orders to handle.**";
                        }
                    }
                }

                //load up the vendor drop downs for the modify vendor tab
                ds = presentation.GetAvailableVendorStatuses();
                ddlVendorStatuses.DataSource = ds.Tables[1];
                ddlVendorStatuses.DataTextField = "StatusName";
                ddlVendorStatuses.DataValueField = "statusID";
                ddlVendorStatuses.DataBind();

                populateModifyVendorDropDown();

                //load up the vendor drop downs for the purchase vendor item tab
                populatePurchaseVendorDropDowns();

                //clear out any success/error messages
                lblCVendorSuccess.Text = "";
                lblMasterError.Text = "";
                lblMVendorSuccess.Text = "";
                lblVendorItemSuccess.Text = "";
                lblModifySuccess.Text = "";

                //disable form fields that need to be disabled at start up
                txtMVendorName.Enabled = false;
                txtMVendorAddress.Enabled = false;
                txtMVendorPhone.Enabled = false;
                ddlVendorStatuses.Enabled = false;
                btnSubmitChanges.Enabled = false;
            }
        }
        #endregion

        private void populateDropDownLists()
        {
            ds = presentation.GetUnits();
            ddlItemUnit.DataSource = ds.Tables[1];
            ddlItemUnit.DataTextField = "unitName";
            ddlItemUnit.DataValueField = "unitID";
            ddlItemUnit.DataBind();

            //modify binds to same units data as add item
            ddlModifyItemUnit.DataSource = ds.Tables[1];
            ddlModifyItemUnit.DataTextField = "unitName";
            ddlModifyItemUnit.DataValueField = "unitID";
            ddlModifyItemUnit.DataBind();

            ds = presentation.GetCategory();
            ddlItemCategory.DataSource = ds.Tables[1];
            ddlItemCategory.DataTextField = "itemCategoryName";
            ddlItemCategory.DataValueField = "itemCategoryID";
            ddlItemCategory.DataBind();

            //modify binds to the same categories as add
            ddlModifyItemCategory.DataSource = ds.Tables[1];
            ddlModifyItemCategory.DataTextField = "itemCategoryName";
            ddlModifyItemCategory.DataValueField = "itemCategoryID";
            ddlModifyItemCategory.DataBind();

            ds = presentation.GetCategory();
            ddlItemCategory2.DataSource = ds.Tables[1];
            ddlItemCategory2.DataTextField = "itemCategoryName";
            ddlItemCategory2.DataValueField = "itemCategoryID";
            ddlItemCategory2.DataBind();

            ds = presentation.GetVendors();
            ddlSelectedVendor.DataSource = ds.Tables[1];
            ddlSelectedVendor.DataTextField = "VendorName";
            ddlSelectedVendor.DataValueField = "VendorID";
            ddlSelectedVendor.DataBind();

            //modify binds to the same vendors as as add item
            ddlModifySelectedVendor.DataSource = ds.Tables[1];
            ddlModifySelectedVendor.DataTextField = "VendorName";
            ddlModifySelectedVendor.DataValueField = "VendorID";
            ddlModifySelectedVendor.DataBind();

            ds = presentation.GetItemAdjustmentReasons();
            DataRow drReasons = ds.Tables[1].NewRow();
            drReasons["AdjName"] = "Choose a Reason";
            drReasons["AdjReasonID"] = "0";
            ds.Tables[1].Rows.InsertAt(drReasons, 0); ;
            ddlModifyAdjustReason.DataSource = ds.Tables[1];
            ddlModifyAdjustReason.DataTextField = "AdjName";
            ddlModifyAdjustReason.DataValueField = "AdjReasonID";
            ddlModifyAdjustReason.DataBind();

            ds = presentation.GetCategory();
            DataRow dr = ds.Tables[1].NewRow();
            dr["itemCategoryName"] = "Choose a Category";
            dr["itemCategoryID"] = "0";
            ds.Tables[1].Rows.InsertAt(dr, 0); ;
            ddlModifyCategory.DataSource = ds.Tables[1];
            ddlModifyCategory.DataTextField = "itemCategoryName";
            ddlModifyCategory.DataValueField = "itemCategoryID";
            ddlModifyCategory.DataBind();

            ds = presentation.GetStoresByType(1);   // Get all central stores
            DataRow drCentralStores = ds.Tables[1].NewRow();
            drCentralStores["storeID"] = "0";
            drCentralStores["storeName"] = "Choose a Store";
            ds.Tables[1].Rows.InsertAt(drCentralStores, 0); ;
            ddlCreateCatCntrlStore.DataSource = ds.Tables[1];
            ddlCreateCatCntrlStore.DataTextField = "storeName";
            ddlCreateCatCntrlStore.DataValueField = "storeID";
            ddlCreateCatCntrlStore.DataBind();
            // Fill in the modify category central store list with the same data
            ddlModCatCntrlStore.DataSource = ds.Tables[1];
            ddlModCatCntrlStore.DataTextField = "storeName";
            ddlModCatCntrlStore.DataValueField = "storeID";
            ddlModCatCntrlStore.DataBind();
        }

        #region Active Tab Control Methods

        /// <summary>
        /// Method handles the changing of tabs.  The far left tab starts at index 0.
        /// Place any code in the designated tab that needs to be changed dynamically each time a the tab is clicked.
        /// </summary>
        /// <param name="sender">object</param>
        /// <param name="e">EventArgs</param>
        protected void TabContainer_ActiveTabChanged(object sender, EventArgs e)
        {
            try
            {
                populateDropDownLists();

                // If "Add Item" became active
                if (TabContainer1.ActiveTabIndex == 0) { }

                // If "Modify Item" became active
                if (TabContainer1.ActiveTabIndex == 1) { }

                // If "Add Vendor" became active
                if (TabContainer1.ActiveTabIndex == 2)
                {
                    lblCVendorSuccess.Text = "";
                    lblMasterError.Text = "";
                }

                // If "Modify Vendor" became active
                if (TabContainer1.ActiveTabIndex == 3)
                {
                    lblMVendorSuccess.Text = "";
                    lblMasterError.Text = "";
                }

                // If "Add/Edit Adjustments" became active
                if (TabContainer1.ActiveTabIndex == 4)
                {
                    lblAddReasonSuccess.Text = "";
                    lblEditReasonSuccess.Text = "";
                }

                // If "Add/Item Category" became active
                if (TabContainer1.ActiveTabIndex == 5)
                {
                    lblAddCategoryError.Text = "";
                    lblAddCategorySuccess.Text = "";
                }
            }
            catch
            {
                throw;
            }
            finally
            {

            }
        }
        #endregion

        #region Buttons

        #region Item Buttons
        protected void btnAddItem_Click(object sender, EventArgs e)
        {
            String itemName = txtItemName.Text;
            String unit = ddlItemUnit.SelectedValue;
            int unitID = Convert.ToInt32(unit);
            double vendorCost = Convert.ToDouble(txtAddItemVendorCost.Text);
            double markupPercent = Convert.ToDouble(txtMarkupPercent.Text);
            String itemCategory = ddlItemCategory.SelectedValue;
            int categoryID = Convert.ToInt32(itemCategory);
            int emergencyQuantity = Convert.ToInt32(txtEmergencyQuantity.Text);
            int minStockQty = Convert.ToInt32(txtAddItemMinStock.Text);
            String vendID = ddlSelectedVendor.Text ;
            int vendorID = Convert.ToInt32(vendID);
            int statusID = Convert.ToInt32(radActiveStatus.SelectedValue);

            DataSet results = presentation.AddItem(itemName, categoryID, unitID, vendorCost, markupPercent, emergencyQuantity, minStockQty, vendorID, statusID);

            // If there was an error while adding the item
            if (results.Tables[0].Rows[0][0].ToString() != "")
            {
                String errorMsg = "The item could not be added: ";
                lblMasterError.Text = errorMsg + results.Tables[0].Rows[0][0].ToString();
                lblCreateSuccess.Text = "";
            }
            else
            {
                // The item was added just fine, reset the form
                txtItemName.Text = "";
                txtAddItemVendorCost.Text = "";
                txtMarkupPercent.Text = "15";
                txtEmergencyQuantity.Text = "";

                lblCreateSuccess.Text = "Item has been Added";
            }
        }

        protected void btnSearch_Click(object sender, EventArgs e)
        {
            gvModifyItem.EditIndex = -1;
            Session.Remove("ItemName");
            Session.Remove("Items");
            itemSearch.searchMethod = 1;
            itemSearch.categorySearched = Convert.ToInt32(ddlItemCategory2.SelectedValue);
            GetItemName();
            ds = presentation.GetItemByCategory(itemSearch.categorySearched);
            items = ds;
            ItemList();
            populateGridviewByName(items);
        }

        protected void btnSearchItemName_Click(object sender, EventArgs e)
        {
            gvModifyItem.EditIndex = -1;
            Session.Remove("ItemName");
            Session.Remove("Items");
            itemSearch.searchMethod = 2;
            itemSearch.itemSearched = txtItemName2.Text;
            GetItemName();
            ds = presentation.GetItemByName(itemSearch.itemSearched);
            items = ds;
            ItemList();
            populateGridviewByName(items);
        }

        protected void btnAddAdjustReason_Click(object sender, EventArgs e)
        {
            String reason = txtAdjusmentReason.Text;
            DataSet ds = presentation.CreateItemAdjustmentReason(reason);

            if (ds.Tables[0].Rows[0][0].ToString() != "")
            {
                lblMasterError.Text = ds.Tables[0].Rows[0][0].ToString();
                lblAddReasonSuccess.Text = "";
            }
            else
            {
                lblMasterError.Text = "";
                lblAddReasonSuccess.Text = "\"" + reason + "\" was successfully added";
            }

            txtAdjusmentReason.Text = "";
            populateDropDownLists();
        }

        protected void btnEditAdjustReason_Click(object sender, EventArgs e)
        {
            String newReason = txtModAdjustReason.Text;
            int adjId = Convert.ToInt32(ddlModifyAdjustReason.SelectedValue);
            DataSet ds = presentation.ModifyItemAdjustmentReason(adjId, newReason);

            if (ds.Tables[0].Rows[0][0].ToString() != "")
            {
                lblMasterError.Text = ds.Tables[0].Rows[0][0].ToString();
                lblAddReasonSuccess.Text = "";
            }
            else
            {
                lblMasterError.Text = "";
                lblEditReasonSuccess.Text = "\"" + newReason + "\" was successfully modified";
            }

            txtAdjusmentReason.Text = "";
            populateDropDownLists();
        }
        #endregion

        #region Vendor Buttons
        /// <summary>
        /// Method saves a new vendor to the database, if errors arise a message is displayed.
        /// Handles the click functionality for the save button under the add vendor tab.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnSave_Click(object sender, EventArgs e)
        {
            //Clear out the error and success labels before attempting the database changes.
            lblMasterError.Text = "";
            lblCVendorSuccess.Text = "";

            //try to add the vendor
            ds = presentation.AddVendor(txtCVendorName.Text, txtCVendorAddress.Text, txtCVendorPhone.Text);
            //counter any errors if any arise, otherwise create the user and reset the 'Create User' form fields to their initial state.
            if (ds.Tables.Count > 0) // If the method returned successfully
            {
                if (ds.Tables[0].Rows[0][0].ToString() != "") // if errors have occurred
                {
                    lblMasterError.Text = ds.Tables[0].Rows[0][0].ToString(); // Error message
                }
                else
                {
                    if (Convert.ToBoolean(ds.Tables[1].Rows[0][0].ToString()))
                    {
                        lblCVendorSuccess.Text = "Vendor \"" + txtCVendorName.Text + "\" added successfully.";
                        
                        //Reset 'Create Vendor' form elements
                        resetForm("create");
                    }
                    else
                        lblMasterError.Text = "Sorry, the vendor could not be added.";
                }
            }
            else
                lblMasterError.Text = "Sorry, the system could not add the vendor."; // If the Data Tier cannot be reached
        }
        /// <summary>
        /// Method handles the selection of a vendor to modify.
        /// Populates the modify vendor form fields and enables the form controls.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnSelectVendor_Click(object sender, EventArgs e)
        {
            //clear out any success or error messages to prepare for drop down selection.
            lblMVendorSuccess.Text = "";
            lblMasterError.Text = "";

            int vendorId = Convert.ToInt32(ddlSelectVendor.SelectedItem.Value);
            ds = presentation.GetVendorByID(vendorId);

            if (ds.Tables.Count > 0) // If the method returned successfully
            {
                if (ds.Tables[0].Rows[0][0].ToString() != "") // if errors have occurred
                {
                    lblMasterError.Text = ds.Tables[0].Rows[0][0].ToString(); // Error message
                }
                else
                {
                    //populate the vendor fields from the database

                    hfVendorID.Value = ds.Tables[1].Rows[0][0].ToString();
                    txtMVendorName.Text = ds.Tables[1].Rows[0][1].ToString();
                    txtMVendorAddress.Text = ds.Tables[1].Rows[0][2].ToString();
                    txtMVendorPhone.Text = ds.Tables[1].Rows[0][3].ToString();
                    ddlVendorStatuses.SelectedValue = ds.Tables[1].Rows[0][4].ToString();

                    //Enable modify vendor fields
                    txtMVendorName.Enabled = true;
                    txtMVendorAddress.Enabled = true;
                    txtMVendorPhone.Enabled = true;
                    btnSubmitChanges.Enabled = true;
                    ddlVendorStatuses.Enabled = true;
                }
            }
            else
            {
                lblMasterError.Text = "Sorry, the system couldn't find the vendor according to the selection.";
            }
        }
        /// <summary>
        /// Method handles the saving of changes to a specific vendor.
        /// Resets the form to be used for another modification to a vendor.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnSubmitChanges_Click(object sender, EventArgs e)
        {
            //clear out any success or error messages to prepare for database attempted changes.
            lblMVendorSuccess.Text = "";
            lblMasterError.Text = "";

            //try to modify/update the vendor's info
            ds = presentation.ModifyVendor(Convert.ToInt32(hfVendorID.Value), txtMVendorName.Text, txtMVendorAddress.Text, txtMVendorPhone.Text, Convert.ToInt32(ddlVendorStatuses.SelectedItem.Value));

            //counter any errors if any arise, otherwise modify/update the user's account information and reset the 'Modify User' form fields to their initial state.
            if (ds.Tables.Count > 0) // If the method returned successfully
            {
                if (ds.Tables[0].Rows[0][0].ToString() != "") // if errors have occurred
                {
                    lblMasterError.Text = ds.Tables[0].Rows[0][0].ToString(); // Error message
                }
                else
                {
                    if (Convert.ToBoolean(ds.Tables[1].Rows[0][0].ToString()))
                    {
                        lblMVendorSuccess.Text = "Vendor \"" + txtMVendorName.Text + "\" updated successfully.";
                        
                        //Reset 'Modify User' form fields
                        resetForm("modify");
                    }
                    else
                        lblMasterError.Text = "Sorry, the vendor could not be updated.";
                }
            }
            else
                lblMasterError.Text = "Sorry, the system could not update the vendor."; // If the Data Tier cannot be reached
        }
        /// <summary>
        /// Method handles the saving of a vendor purchased item in the database.
        /// Resets the form for another insertion of a purchased item in the database.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnSavePurchasedItem_Click(object sender, EventArgs e)
        {
            //Clear out the error and success labels before attempting the database changes.
            lblVendorItemSuccess.Text = "";
            lblMasterError.Text = "";

            //try to add the vendor item
            ds = presentation.AddVendorItem(Convert.ToInt32(ddlItems.SelectedItem.Value), Convert.ToInt32(ddlVendors.SelectedItem.Value), Convert.ToDecimal(txtVendorCost.Text), txtPurchaseDate.Text, Convert.ToInt32(txtVItemQuantity.Text));
            //counter any errors if any arise, otherwise create the user and reset the 'Create User' form fields to their initial state.
            if (ds.Tables.Count > 0) // If the method returned successfully
            {
                if (ds.Tables[0].Rows[0][0].ToString() != "") // if errors have occurred
                {
                    lblMasterError.Text = ds.Tables[0].Rows[0][0].ToString(); // Error message
                }
                else
                {
                    if (Convert.ToBoolean(ds.Tables[1].Rows[0][0].ToString()))
                    {
                        lblVendorItemSuccess.Text = "Added purchased vendor item successfully.";

                        //Reset 'Add Purchased Vendor Item' form elements
                        resetForm("purchase");
                    }
                    else
                        lblMasterError.Text = "Sorry, the purchase vendor item could not be added.";
                }
            }
            else
                lblMasterError.Text = "Sorry, the system could not add the purchased vendor item."; // If the Data Tier cannot be reached
        }

        // Added by Jason Vance, 14 November 2012
        /// <summary>
        /// Adds the category that was entered by the user
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnAddCategory_Click(object sender, EventArgs e)
        {
            String storeId = ddlCreateCatCntrlStore.SelectedValue;
            String catName = txtCategoryName.Text;
            DataSet ds = presentation.AddCategory(catName, storeId);

            if (ds.Tables[0].Rows[0][0].ToString() == "")
            {
                // Everything worked
                lblAddCategoryError.Text = "";
                lblAddCategorySuccess.Text = "\"" + catName + "\" was added";
                txtCategoryName.Text = "";
                populateDropDownLists();
            }
            else
            {
                // Something went wrong
                lblAddCategorySuccess.Text = "";
                lblAddCategoryError.Text = ds.Tables[0].Rows[0][0].ToString();
            }
        }

        // Added by Jason Vance, 14 November 2012
        /// <summary>
        /// Modifies the category that was chosen by the user
        /// Changes the category to the name entered by the user
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnModifyCategory_Click(object sender, EventArgs e)
        {
            String storeId = ddlModCatCntrlStore.SelectedValue;

            int catId = Convert.ToInt32(ddlModifyCategory.SelectedValue);
            DataSet ds = presentation.GetCategory();
            String oldCatName = "";

            foreach (DataRow row in ds.Tables[1].Rows)
            {
                if (row["itemCategoryId"].ToString() == "" + catId)
                {
                    oldCatName = row["itemCategoryName"].ToString();
                }
            }

            String newCatName = txtModifyCategoryName.Text;
            ds = presentation.ModifyCategory(catId, newCatName, storeId);

            if (ds.Tables[0].Rows[0][0].ToString() == "")
            {
                // Everything worked
                lblAddCategoryError.Text = "";
                lblAddCategorySuccess.Text = "\"" + oldCatName + "\" was changed to \"" + newCatName + "\"";
                txtModifyCategoryName.Text = "";
                populateDropDownLists();
            }
            else
            {
                // Something went wrong
                lblAddCategorySuccess.Text = "";
                lblAddCategoryError.Text = ds.Tables[0].Rows[0][0].ToString();
            }
        }

        protected void ddlModifyCategory_Changed(object sender, EventArgs e)
        {
            String category = ddlModifyCategory.SelectedItem.ToString();
            if (category == "Choose a Category")
            {
                category = "";
            }
            txtModifyCategoryName.Text = category;
        }

        protected void ddlModifyAdjustReason_Changed(object sender, EventArgs e)
        {
            String reason = ddlModifyAdjustReason.SelectedItem.ToString();
            if (reason == "Choose a Reason")
            {
                reason = "";
            }
            txtModAdjustReason.Text = reason;
        }

        #endregion

        #endregion

        #region Gridview Controls
        protected void populateGridviewByName(DataSet i)
        {

            if (i.Tables[0].Rows[0][0].ToString() != "")
            {
                string me = ds.Tables[0].Rows[0][0].ToString();
                lblMasterError.Text = me;

                gvModifyItem.DataSource = null;
                gvModifyItem.DataBind();
            }
            else
            {
                gvModifyItem.DataSource = i.Tables[1];
                gvModifyItem.DataBind();
                lblMasterError.Text = "";
            }
        }

        /*protected void gvModifyItem_RowEditing(object sender, GridViewEditEventArgs e)
        {
            gvModifyItem.AllowSorting = false;

            GridViewRow row = gvModifyItem.Rows[e.NewEditIndex];
            gvModifyItem.EditIndex = e.NewEditIndex;
            cost = ((Label)row.FindControl("lblEditCost")).Text;
            cost = String.Format("{0:0.00}", cost);
            cost = cost.Replace(",", "");
            itemSearch.itemCategory = ((Label)row.FindControl("lblCategoryID")).Text;
            itemSearch.store = ((Label)row.FindControl("lblStore")).Text;
            items = ItemList();
            populateGridviewByName(items);
        }

        protected void gvModifyItem_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
        {
            gvModifyItem.AllowSorting = true;

            items = ItemList();
            gvModifyItem.EditIndex = -1;
            itemSearch = GetItemName();
            populateGridviewByName(items);
        }

        protected void gvModifyItem_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {
            gvModifyItem.AllowSorting = true;

            GridViewRow row = gvModifyItem.Rows[e.RowIndex];
            int itemID = Convert.ToInt32(((Label)row.FindControl("lblEditID")).Text);
            string name = ((TextBox)row.FindControl("txtEditName")).Text;
            double markup = Convert.ToDouble(((TextBox)row.FindControl("txtEditCost")).Text);
            int itemCat = Convert.ToInt32(((DropDownList)row.FindControl("ddlEditCategoryID")).SelectedValue);
            int storeid = Convert.ToInt32(((DropDownList)row.FindControl("ddlSelectingStore")).SelectedValue);

            DataSet ds = presentation.ModifyItem(itemID, 3, name, 10, markup, itemCat, storeid);
            String errorMessage = ds.Tables[0].Rows[0][0].ToString();

            gvModifyItem.EditIndex = -1;

            itemSearch = GetItemName();
            if (itemSearch.searchMethod == 1)
            {
                items = presentation.GetItemByCategory(itemSearch.categorySearched);
            }
            else if (itemSearch.searchMethod == 2)
            {
                items = presentation.GetItemByName(itemSearch.itemSearched);
            }
            Session.Remove("Items");
            ItemList();
            populateGridviewByName(items);

            //reset the purchase vendor item tab to account for the item changes
            resetForm("purchase");

            // Check for errors in modifying item
            if (errorMessage.Length > 0)
            {
                lblMasterError.Text = errorMessage;
            }
        }*/

        protected void gvModifyItem_RowDataBound(object sender, GridViewRowEventArgs e)
        {

            if (e.Row.RowType == DataControlRowType.DataRow &&
                (e.Row.RowState & DataControlRowState.Edit) == DataControlRowState.Edit)
            {
                ds = presentation.GetCategory();
                ((DropDownList)e.Row.FindControl("ddlEditCategoryID")).DataSource = ds.Tables[1];
                ((DropDownList)e.Row.FindControl("ddlEditCategoryID")).DataTextField = "itemCategoryName";
                ((DropDownList)e.Row.FindControl("ddlEditCategoryID")).DataValueField = "itemCategoryID";
                ((DropDownList)e.Row.FindControl("ddlEditCategoryID")).DataBind();
                ((DropDownList)e.Row.FindControl("ddlEditCategoryID")).SelectedValue = itemSearch.itemCategory;

                ds = presentation.GetActiveCentralStores();
                ((DropDownList)e.Row.FindControl("ddlSelectingStore")).DataSource = ds.Tables[1];
                ((DropDownList)e.Row.FindControl("ddlSelectingStore")).DataTextField = "storeName";
                ((DropDownList)e.Row.FindControl("ddlSelectingStore")).DataValueField = "storeID";
                ((DropDownList)e.Row.FindControl("ddlSelectingStore")).DataBind();
                ((DropDownList)e.Row.FindControl("ddlSelectingStore")).SelectedValue = itemSearch.store;

                ((TextBox)e.Row.FindControl("txtEditCost")).Text = cost;
            }

        }

        protected void gvModifyItem_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            items = ItemList();
            gvModifyItem.PageIndex = e.NewPageIndex;
            gvModifyItem.DataBind();
            populateGridviewByName(items);

        }
        #endregion

        #region Session Control
        //Create and retrieve session
        private Application_Classes.ItemSearch GetItemName()
        {
            if (Session["ItemName"] == null)
                Session.Add("ItemName", itemSearch);

            return (Application_Classes.ItemSearch)Session["ItemName"];
        }

        private DataSet ItemList()
        {
            if (Session["Items"] == null)
                Session.Add("Items", items);
            return (DataSet)Session["Items"];
        }
        #endregion Session Control

        #region Session Methods
        private int GetStoreID()
        {
            User lg = (User)Session["LoggedInUser"];
            return lg.getStoreId();
        }
        private string GetFirstName()
        {
            User lg = (User)Session["LoggedInUser"];
            return lg.getFirstName();
        }
        private string GetLastName()
        {
            User lg = (User)Session["LoggedInUser"];
            return lg.getLastName();
        }
        private string GetSessionID()
        {
            try
            {
                User lg = (User)Session["LoggedInUser"];
                return lg.getSessionId();
            }
            catch (Exception ex)
            {
                ex.Message.ToString();
                return null;
            }
        }
        private bool GetIsAdmin()
        {
            User lg = (User)Session["LoggedInUser"];
            return lg.getIsAdmin();
        }
        private bool GetIsGeneralManager()
        {
            User lg = (User)Session["LoggedInUser"];
            return lg.getIsGeneralManager();
        }
        private bool GetIsStoreManager()
        {
            User lg = (User)Session["LoggedInUser"];
            return lg.getIsStoreManager();
        }
        private bool GetIsStoreKeeper()
        {
            User lg = (User)Session["LoggedInUser"];
            return lg.getIsStoreKeeper();
        }
        private bool GetIsSubUnitClerk()
        {
            User lg = (User)Session["LoggedInUser"];
            return lg.getIsSubUnitClerk();
        }
        private bool GetIsAccounting()
        {
            User lg = (User)Session["LoggedInUser"];
            return lg.getIsAccounting();
        }
        private bool GetIsProcurement()
        {
            User lg = (User)Session["LoggedInUser"];
            return lg.getIsProcurement();
        }
        private bool GetIsCEO()
        {
            User lg = (User)Session["LoggedInUser"];
            return lg.getIsCEO();
        }
        #endregion

        #region Vendor Methods
        /// <summary>
        /// Method resets all the form fields for the designated tab
        /// </summary>
        /// <param name="tabFormType">string - tab name for form to be reset, valid types: 'create', 'modify', or 'purchase'</param>
        public void resetForm(string tabFormType)
        {
            //reset create tab form fields to initial state to allow for another possible user creation.
            if (tabFormType.Equals("create"))
            {
                txtCVendorName.Text = "";
                txtCVendorAddress.Text = "";
                txtCVendorPhone.Text = "";

                //reset the modify vendor/purchase vendor item tabs to account for the newly created vendor
                resetForm("modify");
                resetForm("purchase");
            }
            //reset modify tab form fields to initial state to allow for another possible user account modification.
            else if (tabFormType.Equals("modify"))
            {
                txtMVendorName.Text = "";
                txtMVendorAddress.Text = "";
                txtMVendorPhone.Text = "";
                hfVendorID.Value = "";
                ddlVendorStatuses.SelectedIndex = 0;

                //disable all form fields
                txtMVendorName.Enabled = false;
                txtMVendorAddress.Enabled = false;
                txtMVendorPhone.Enabled = false;
                ddlVendorStatuses.Enabled = false;
                btnSubmitChanges.Enabled = false;

                //repopulate the select vendor drop down
                populateModifyVendorDropDown();

                //reset the purchase vendor item tab to account for the vendor changes
                resetForm("purchase");
            }
            //reset the purchase vendor item form fields to initial state to allow for another possible vendor item creation.
            else if (tabFormType.Equals("purchase"))
            {
                txtPurchaseDate.Text = "";
                txtVItemQuantity.Text = "";
                txtVendorCost.Text = "";
                ddlVendors.SelectedIndex = 0;
                ddlItems.SelectedIndex = 0;

                populatePurchaseVendorDropDowns();
            }
        }
        /// <summary>
        /// Method populates the select vendor drop down in the modify vendor tab.
        /// </summary>
        public void populateModifyVendorDropDown()
        {
            //load up the vendor drop down for the modify vendor tab
            ds = presentation.GetVendors();
            ddlSelectVendor.DataSource = ds.Tables[1];
            ddlSelectVendor.DataTextField = "vendorName";
            ddlSelectVendor.DataValueField = "vendorID";
            ddlSelectVendor.DataBind();
        }
        /// <summary>
        /// Method populates the purchase vendor items drop downs.
        /// </summary>
        public void populatePurchaseVendorDropDowns()
        {
            //load up the vendor drop down for the purchase vendor item tab
            ds = presentation.GetActiveVendors();
            ddlVendors.DataSource = ds.Tables[1];
            ddlVendors.DataTextField = "vendorName";
            ddlVendors.DataValueField = "vendorID";
            ddlVendors.DataBind();

            //load up the items drop down in the purchase vendor item tab
            ds = presentation.GetItems();
            ddlItems.DataSource = ds.Tables[1];
            ddlItems.DataTextField = "ItemName";
            ddlItems.DataValueField = "ItemID";
            ddlItems.DataBind();
        }
        #endregion


        //Created by Jason Vance 10-31-2012
        protected void gvModifyItem_Sorting(object sender, GridViewSortEventArgs e)
        {
            // Sort the data
            if (ModifyItemSortDirection == SortDirection.Ascending)
            {
                ModifyItemSortDirection = SortDirection.Descending;
                SortModifyItemGridView(e.SortExpression, "DESC");
            }
            else
            {
                ModifyItemSortDirection = SortDirection.Ascending;
                SortModifyItemGridView(e.SortExpression, "ASC");
            }
        }

        //Created by Jason Vance 10-31-2012
        /// <summary>
        /// Keep track of Allocation's specific sort direction between posts.
        /// </summary>
        public SortDirection ModifyItemSortDirection
        {
            get
            {
                if (Session["modifyItemSortDirection"] == null)
                    Session["modifyItemSortDirection"] = SortDirection.Ascending;

                return (SortDirection)Session["modifyItemSortDirection"];
            }
            set { Session["modifyItemSortDirection"] = value; }
        }

        //Created by Jason Vance 10-31-2012
        /// <summary>
        /// This does the actual work of sorting the data that will be put into gvItemSearch
        /// </summary>
        private void SortModifyItemGridView(String sortExpression, String direction)
        {
            items = ItemList();

            DataTable dt = items.Tables[1];

            //Sorting with DataView
            DataView dv = new DataView(dt);
            dv.Sort = sortExpression + " " + direction;

            //replace original table into Dataset with sorted table
            items.Tables.RemoveAt(1);
            items.Tables.Add(dv.ToTable());

            //Call binding method
            populateGridviewByName(items);
        }

        //Adam Venezia 11-24-12 send off template data to presentation to validate and pass on to DataTier.
        protected void btnCommitModifyItem_Click(object sender, EventArgs e)
        {
            int itemID = Convert.ToInt32(lblModifyItemID.Text);
            String itemName = txtModifyItemName.Text;
            int unitID = Convert.ToInt32(ddlModifyItemUnit.SelectedValue);
            double vendorCost = Convert.ToDouble(txtModifyItemVendorCost.Text);
            double markupPercent = Convert.ToDouble(txtModifyMarkupPercent.Text);
            int categoryID = Convert.ToInt32(ddlModifyItemCategory.SelectedValue);
            int emergencyQty = Convert.ToInt32(txtModifyEmergencyQuantity.Text);
            int vendorID = Convert.ToInt32(ddlModifySelectedVendor.SelectedValue);
            int statusID = Convert.ToInt32(radModifyActiveStatus.SelectedValue);

            ds = presentation.ModifyItem(itemID, itemName, unitID, vendorCost, categoryID, emergencyQty,
                markupPercent, vendorID, statusID);

            // If there was an error while adding the item
            if (ds.Tables[0].Rows[0][0].ToString() != "")
            {
                String errorMsg = "The item could not be modified: ";
                lblMasterError.Text = errorMsg + ds.Tables[0].Rows[0][0].ToString();
                lblModifySuccess.Text = "";
            }
            else
            {
                // The item was added just fine
                lblModifySuccess.Text = "Item has been Modified.";
            }
        }

        //Go back to the search panel, from the modify action panel, after clearing the modify template.
        //Adam Venezia 11-24-12
        protected void btnReturnToSearch_Click(object sender, EventArgs e)
        {
            clearModifyTemplate();
            pnlModifyAction.Visible = false;
            pnlModifySearch.Visible = true;
        }

        /// <summary>
        /// Quick for each loop against all the controls contained within pnlModifyAction panel to clear their text or selection.
        /// Adam Venezia 11-24-12
        /// </summary>
        private void clearModifyTemplate()
        {
            TextBox txt;
            DropDownList ddl;

            foreach (Control c in pnlModifyAction.Controls)
            {
                if ((txt = c as TextBox) != null)
                    txt.Text = "";
                else if ((ddl = c as DropDownList) != null)
                    ddl.ClearSelection();
            }

            radModifyActiveStatus.ClearSelection();
        }

        //Adam Venezia 11-24-12; Getting the item that was clicked to edit. Fill in edit template or present the error.
        protected void gvModifyItem_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            if (e.CommandName == "ItemEdit")
            {
                int index = Convert.ToInt32(e.CommandArgument);
                GridViewRow row = gvModifyItem.Rows[index];

                ds = presentation.GetModifyInfoByID(Convert.ToInt32((row.FindControl("lblItemID") as Label).Text));

                if (ds.Tables[0].Rows[0][0].ToString() == "")
                {
                    //swapping views.
                    pnlModifyAction.Visible = true;
                    pnlModifySearch.Visible = false;

                    //short cut to this row.
                    DataRow dr = ds.Tables[1].Rows[0];

                    //fill in template
                    lblModifyItemID.Text = dr["itemID"].ToString(); //persist retrieved id; hidden field
                    txtModifyItemName.Text = dr["itemName"].ToString();
                    ddlModifyItemCategory.SelectedValue = dr["itemCategoryID"].ToString(); //value is ID; text is name; selecting value will show us the proper name
                    ddlModifyItemUnit.SelectedValue = dr["unitID"].ToString();
                    txtModifyItemVendorCost.Text = String.Format("{0:0.00}", Convert.ToDouble(dr["VendorCost"].ToString())); //chop off some trailing 0s
                    txtModifyMarkupPercent.Text = String.Format("{0:0}", ((Convert.ToDouble(dr["MarkupMultiplier"].ToString()) - 1) * 100)); //make sure we print out a whole number; database represents it as 1.15 for 15%
                    txtModifyEmergencyQuantity.Text = dr["EmergencyQty"].ToString();
                    txtModItemMinStock.Text = dr["minStockQty"].ToString();
                    ddlModifySelectedVendor.SelectedValue = dr["VendorID"].ToString();
                    radModifyActiveStatus.SelectedValue = dr["statusID"].ToString();
                }
                else
                {
                    lblMasterError.Text = ds.Tables[0].Rows[0][0].ToString();
                }
            }
        }
    }
}